import random
import tkinter as tk
from tkinter import scrolledtext

# 从本地文件加载英语单词列表
def load_words():
    file_path = "E:/nltk_data/en.txt"  # 修改为你的文件路径
    with open(file_path, 'r', encoding='utf-8') as file:
        words = file.read().splitlines()
    return words

# 获取随机单词
def get_random_word(words):
    return random.choice(words).lower()

# 判断单词是否在数据库中
def is_word_in_database(word, words):
    return word.lower() in words

# 获取机器接龙的单词
def get_machine_word(last_word, words):
    last_char = last_word[-1]
    available_words = [word for word in words if word[0].lower() == last_char]

    if available_words:
        return random.choice(available_words).lower()
    else:
        return None

# 获取提示
def get_hint(last_word, words):
    last_char = last_word[-1]
    hints = [word for word in words if word[0].lower() == last_char]

    if hints:
        return random.choice(hints).lower()
    else:
        return None

# 单词接龙游戏
def word_solitaire_game(root, words):
    def start_game():
        global current_word
        current_word = get_random_word(words)
        text.insert(tk.END, f"Machine gives word: {current_word}\n")
        text.insert(tk.END, "Enter a word (type 'hint' for a hint, type 'end' to end the game):\n")
        text.see(tk.END)
        text.focus()

    def on_return(event):
        global current_word
        user_input = text.get("insert linestart", "insert lineend").strip().lower()
        text.insert(tk.END, f"{user_input}\n")
        text.see(tk.END)

        if user_input == "end":
            text.insert(tk.END, "Game over!\n")
            start_game()
            return
        elif user_input == "hint":
            hint = get_hint(current_word, words)
            if hint:
                text.insert(tk.END, f"Hint: {hint}\n")
            else:
                text.insert(tk.END, "No more hints available, please try.\n")
            text.insert(tk.END, "Enter a word (type 'hint' for a hint, type 'end' to end the game):\n")
            text.see(tk.END)
            text.focus()
            return

        last_char = current_word[-1]
        user_first_char = user_input[0]

        if user_first_char != last_char:
            text.insert(tk.END, f"Incorrect word chain, should start with '{last_char}'. Please re-enter.\n")
            text.insert(tk.END, "Enter a word (type 'hint' for a hint, type 'end' to end the game):\n")
            text.see(tk.END)
            text.focus()
            return

        if not is_word_in_database(user_input, words):
            text.insert(tk.END, "The word is not in the database.\n")
            text.insert(tk.END, "Enter 'Y' to modify the word, 'N' to not modify.\n")
            text.bind("<Return>", lambda e: handle_choice(e, user_input))
            return

        process_user_input(user_input)

    def handle_choice(event, previous_input):
        choice = text.get("insert linestart", "insert lineend").strip().upper()
        text.insert(tk.END, f"{choice}\n")
        text.see(tk.END)
        if choice == 'Y':
            text.insert(tk.END, "Please re-enter a valid word:\n")
            text.see(tk.END)
            text.focus()
        elif choice == 'N':
            text.insert(tk.END, "User chose not to modify, machine will continue.\n")
            text.see(tk.END)
            process_user_input(previous_input)
        else:
            text.insert(tk.END, "Invalid choice, please enter 'Y' or 'N'.\n")
            text.see(tk.END)
            text.focus()

    def process_user_input(user_input):
        global current_word
        text.insert(tk.END, f"User gives word: {user_input}\n")
        machine_word = get_machine_word(user_input, words)
        if machine_word:
            text.insert(tk.END, f"Machine continues with word: {machine_word}\n")
            current_word = machine_word
        else:
            text.insert(tk.END, "Machine cannot continue, game over!\n")
            start_game()
        text.insert(tk.END, "Enter a word (type 'hint' for a hint, type 'end' to end the game):\n")
        text.bind("<Return>", on_return)
        text.see(tk.END)
        text.focus()

    root.title("Word Solitaire Game")
    root.geometry("600x400")

    text = scrolledtext.ScrolledText(root, width=70, height=15, font=("Courier New", 12), wrap=tk.WORD)
    text.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
    text.bind("<Return>", on_return)

    # 设置文本框的初始内容
    text.insert(tk.END, "Welcome to Word Solitaire Game!\n")
    text.insert(tk.END, "Enter a word in the input box below and press Enter.\n")
    text.insert(tk.END, "Type 'hint' for a hint, type 'end' to end the game.\n\n")

    start_game()

# 主函数
if __name__ == "__main__":
    words_list = load_words()
    print(f"There are {len(words_list)} words in the database.")

    root = tk.Tk()
    word_solitaire_game(root, words_list)
    root.mainloop()